﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Data;
using WMS.FC.Domain.DomainObject.Menu;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.PersistenceObject.History;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.Menu.Interface;
using WMS.FC.Domain.Service.System;

namespace WMS.FC.Domain.Service.Menu
{
    public class GenerateColumnService : ServiceBase, IGenerateColumnService
    {
        protected readonly Dictionary<string, string> NameDic = new Dictionary<string, string>()
        {
            {"id","主键"},
            {"create_date","创建时间"},
            {"created_by","创建人" },
            {"modify_date","修改时间" },
            {"modified_by","修改人" },
            {"modify_ip","修改人IP" },
            {"is_deleted","是否软删除" },
            {"timestamp","并发令牌" },
            {"warehouse_code","仓库编码" },
            {"line_code","产线编码" },
        };

        protected readonly List<string> SystemField = new List<string>()
        {
            "id","create_date","created_by","created_by","modify_date","modified_by","modify_ip","is_deleted","timestamp","warehouse_code"
        };

        protected readonly List<string> SystemDateField = new List<string>()
        {
            "create_date","modify_date"
        };

        protected readonly List<string> SystemBoolField = new List<string>()
        {
            "is_deleted"
        };

        protected readonly ISystemRepository systemRepository;
        protected readonly ISplitTableRepository splitTableRepository;

        public GenerateColumnService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            ISystemRepository systemRepository,
            ISplitTableRepository splitTableRepository)
            : base(logger, options, mapper)
        {
            this.systemRepository = systemRepository;
            this.splitTableRepository = splitTableRepository;
        }

        public async Task<ActionResult<List<ColumnDO>>> GenerateColumn(string sql, UserInfo userInfo)
        {
            var result = new ActionResult<List<ColumnDO>>("生成列");
            try
            {
                if (string.IsNullOrWhiteSpace(sql))
                    return result.ArgumentError("SQL语句不能为空");

                if (sql.StartsWith("HIS:"))
                {
                    var typeName = sql.Replace("HIS:", "");
                    var entityType = Type.GetType($"WMS.FC.Domain.PersistenceObject.History.{typeName}");
                    if (entityType == null)
                        return result.BusinessError($"类型:{typeName},未找到");

                    var entityInfo = await splitTableRepository.GetSplitTableEntityInfo(entityType);
                    result.Data = entityInfo.ColumnList.Select(item =>
                    {
                        var field = item.Value.ColumnName.ToLower();
                        return new ColumnDO()
                        {
                            Field = field,
                            NameCN = NameDic.ContainsKey(field) ? NameDic[field] : "",
                            NameEN = item.Value.ColumnName,
                            Width = "",
                            IsReadonly = false,
                            IsHidden = SystemField.Contains(field),
                            IsSearchable = false,
                            DataSource = "",
                            ControlTypeCode = SystemDateField.Contains(field) ? "ControlType_DateTime" : SystemBoolField.Contains(field) ? "ControlType_Boolean" : "ControlType_String",
                            Rules = new List<ColumnRuleDO>()
                        };
                    }).ToList();
                }
                else
                {
                    var dataTable = await systemRepository.ExecuteQuerySchema(sql);
                    if (dataTable == null)
                        return result.DbError("SQL语句查询异常");

                    result.Data = dataTable.AsEnumerable().Select(row =>
                    {
                        var field = row["ColumnName"].ToString()!.ToLower();
                        return new ColumnDO()
                        {
                            Field = field,
                            NameCN = NameDic.ContainsKey(field) ? NameDic[field] : "",
                            NameEN = row["ColumnName"].ToString()!,
                            Width = "",
                            IsReadonly = false,
                            IsHidden = SystemField.Contains(field),
                            IsSearchable = false,
                            DataSource = "",
                            ControlTypeCode = SystemDateField.Contains(field) ? "ControlType_DateTime" : SystemBoolField.Contains(field) ? "ControlType_Boolean" : "ControlType_String",
                            Rules = new List<ColumnRuleDO>()
                        };
                    }).ToList();
                }
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
